package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojo.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult login(AdUserDto dto) {
        //检查参数
        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "用户名或密码不能为空");
        }
        //根据用户名查询用户是否存在
        AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "用户名不存在");
        }
        //判断用户账号密码是否一致
        String userPassword = user.getPassword();
        String newPassword = DigestUtils.md5DigestAsHex((dto.getPassword() + user.getSalt()).getBytes());
        if (! userPassword.equals(newPassword)) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "密码错误，请重新输入");
        }
        //判断用户状态
        if (user.getStatus().intValue() != 9) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR, "用户状态异常");
        }
        //修改最近登录时间
        user.setLoginTime(new Date());
        updateById(user);
        //颁发token
        String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));
        //返回封装结果
        Map map = new HashMap<>();
        map.put("token", token);
        AdUserVO userVO = new AdUserVO();
        BeanUtils.copyProperties(user, userVO);
        map.put("user", userVO);
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult register(AdUser user) {
        //检查参数
        if (StringUtils.isBlank(user.getName()) || StringUtils.isBlank(user.getPassword())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "用户名或密码不能为空");
        }
        //判断用户名和密码是否重复
        int nameCount = count(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, user.getName()));
        if (nameCount > 0 ) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST, "用户名已存在，请更换一个新的用户名");
        }
        //创建新用户
        String salt = RandomStringUtils.randomAlphabetic(8);
        String password = user.getPassword();
        user.setPassword(DigestUtils.md5DigestAsHex((password + salt).getBytes()));
        user.setSalt(salt);
        user.setCreatedTime(new Date());
        user.setStatus(9);
        save(user);
        //返回结果
        return ResponseResult.okResult();
    }
}
